import {Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams} from 'ionic-angular';
import {AppGlobal, AppService} from "../../app/app.service";
import {LoginPage} from "../login/login";

/**
 * Generated class for the MyRepositoryPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-my-repository',
  templateUrl: 'my-repository.html',
})
export class MyRepositoryPage {
  hasmore = true;
  repository: any;
  repositoryall: any;
  user: any;
  spinner1: boolean = true;
  loginsts:any;
  params = {pageNo: 1, pageSize:20, user_id: ''};

  @ViewChild(Content) content: Content;

  constructor(public navCtrl: NavController, public navParams: NavParams, public appService: AppService) {
    //登录后操作
    this.loginsts = localStorage.getItem('loginsts');
    //电脑测试
    //this.loginsts = "1";
    if (!(this.loginsts == "1")){
      this.navCtrl.push(LoginPage);
    }
    this.user = this.navParams.get("user");
    /*电脑测试
    this.user = {
      avatar:'assets/icon/user.jpg',
      nickname:'未名',
      user_id:'未登录',
      companyname:'未名'
    };*/

  }

  ionViewDidLoad() {
    this.getFavoritesItems();
    console.log('ionViewDidLoad RepositoryListPage');
  }

  getFavoritesItems() {
    //this.params.user_id = this.user.user_id;
    this.params.user_id = '13064049491';
      this.appService.httpGet(AppGlobal.API.getRepositorybyuser, this.params, d => {
      this.repository = d.data;
      if(this.repository.length <= 0){
        this.hasmore = false;
        console.log("没有数据！")
      }
      this.repositoryall = this.repository;
      this.params.pageNo += 1;
      this.spinner1 = false;
    });
  }

  doInfinite(infiniteScroll) {
    if (this.hasmore == false) {
      infiniteScroll.complete();
      return;
    }
    this.appService.httpGet(AppGlobal.API.getRepositorybyuser, this.params, d => {
      if (d.data.length > 0) {
        this.repository = this.repository.concat(d.data);
        this.repositoryall = this.repository;
        this.params.pageNo += 1;
      } else {
        this.hasmore = false;
        console.log("没有数据啦！")
      }
      infiniteScroll.complete();
    });
  }

  getItems(e: any) {
    //获取文本框里的 value
    var searchText = e.target.value == undefined ? '' : e.target.value.trim();
    console.log(searchText);
    if (searchText && searchText.trim() != '') {
      this.repository = this.repository.filter((item) => {
        let label = item.title;
        return (label.toLowerCase().indexOf(searchText.toLowerCase()) > -1);
      })
    } else {
      console.log(this.repositoryall);
      this.repository = this.repositoryall;
    }
  }

  //增加知识库
  addRepository(){
    this.navCtrl.push('RepositoryAddPage');
  }
}
